using System;
using System.Web;
using System.Web.UI;

namespace Framework.Library.Utilities
{
	public class RefreshPage : System.Web.UI.Page
	{
		#region Constants
		// Constants
		public  const string RefreshTicketCounter = "RefreshTicketCounter";
		private const string SetFocusFunctionName = "__setFocus";
		private const string SetFocusScriptName	  = "__inputFocusHandler";
		#endregion

		public RefreshPage()
		{
			// Register a PreRender handler
			this.PreRender += new EventHandler(RefreshPage_PreRender);
		}// func

		// Indicates if the page is being viewed in response to F5 hit
		public bool IsPageRefresh
		{
			get 
			{
				object obj = HttpContext.Current.Items[RefreshAction.PageRefreshEntry];
				if( obj == null )
					return false;
				return (bool)obj; 
			}
		}// func

		// Increase the internal counter used to generate refresh tickets
		public void TrackRefreshState()
		{
			InitRefreshState();
			int ticket = Convert.ToInt32( Session[RefreshTicketCounter] ) + 1;
			Session[RefreshTicketCounter] = ticket;
		}// func


		#region Private Members
		// Create the hidden field to store the current request ticket
		private void SaveRefreshState()
		{
			int ticket = Convert.ToInt32( Session[RefreshTicketCounter] ) + 1;
			RegisterHiddenField( RefreshAction.CurrentRefreshTicketEntry, ticket.ToString() ); 
		}// func

		// Ensure that the ticket counter is initialized
		private void InitRefreshState()
		{
			if( Session[RefreshTicketCounter] == null )
				Session[RefreshTicketCounter] = 0;	
		}// func

		// Handle the PreRender event
		private void RefreshPage_PreRender(object sender, EventArgs evt)
		{
			SaveRefreshState();
		}// func

		#endregion

	}// class
}
